package com.bwie.auth.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.bwie.auth.exception.LoginException;
import com.bwie.auth.remote.UserRemote;
import com.bwie.auth.service.AuthUserService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.LoginConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Menu;
import com.bwie.common.domain.Role;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserRequest;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: AuthUserServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 张雨乐
 * @date: 2025/9/1 9:20
 */
@Service
public class AuthUserServiceImpl implements AuthUserService {
    @Autowired
    private UserRemote userRemote;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    HttpServletRequest request;
    @Override
    public Result getCode(String phone) {
        if (StrUtil.isBlank(phone)) {
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }

        Result<User>userResult=userRemote.phone(phone);
        User user = userResult.getData();
        if (user==null){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        String s = RandomUtil.randomNumbers(4);
        redisTemplate.opsForValue().set(phone,s,1, TimeUnit.MINUTES);
//        rabbitTemplate.convertAndSend("code",phone);
        return Result.success("成功");
    }

    /**
     * 登录
     * @param userRequest
     * @return
     */
    @Override
    public Result login(UserRequest userRequest) {
        String phone = userRequest.getPhone();
        String code = userRequest.getCode();
        String pwd = userRequest.getPwd();
        if (StrUtil.isBlank(pwd)){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        if (StrUtil.isBlank(phone)){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        if (StrUtil.isBlank(code)){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        String getCode = (String) redisTemplate.opsForValue().get(phone);
        if (!code.equals(getCode)){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        Result<User>userResult=userRemote.phone(phone);
        User user = userResult.getData();
        if (user==null){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        if (!user.getPwd().equals(pwd)){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        //查看我的角色传给前台
        Result<List<Role>>result=userRemote.getRole(user.getId());
        List<Role> roleList = result.getData();
        Map<String, Object> map = new HashMap<>();
        String userKey = IdUtil.fastSimpleUUID();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,user,30, TimeUnit.MINUTES);
        UserResponse userResponse = new UserResponse();
        userResponse.setTime("30Time");
        userResponse.setUser(user);
       userResponse.setRoleList(roleList);
       userResponse.setToken(token);
        return Result.success(userResponse);
    }

    @Override
    public Result role(String id) {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (user==null){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        redisTemplate.opsForValue().set(JwtConstants.DETAILS_USER_ID+user.getId(),id,30,TimeUnit.MINUTES);
        return Result.success("选择成功");
    }

    @Override
    public Result menu() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (user==null){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        String roleId = (String) redisTemplate.opsForValue().get(JwtConstants.DETAILS_USER_ID + user.getId());
        if (StrUtil.isBlank(roleId)){
            throw new LoginException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        Result<List<Menu>>listResult=userRemote.menu(roleId);
        List<Menu> data = listResult.getData();
        List<Menu>list=digui(data,0);
        return Result.success(list);
    }

    private List<Menu> digui(List<Menu> data, int i) {
        List<Menu> objects = new ArrayList<>();
        for (Menu datum : data) {
            if (datum.getFid().equals(i)){
                List<Menu> digui = digui(data, datum.getId());
                datum.setMenus(digui);
                objects.add(datum);
            }
        }
        return objects;
    }
}
